/*
 * @Author: yc
 * @Date: 2020-05-29 10:47:54
 * @LastEditTime: 2020-05-31 12:19:12
 * @FilePath: \react-admin\src\redux\actions\notifications.js
 */
import {
  postNotificationAsReadById,
  postAllNotificationAsRead,
  getNotifications
} from '@/requests/api/notification.js'

export const actionTypes = {
  START_NOTIFICATION_POST: 'START_NOTIFICATION_POST',
  FINISH_NOTIFICATION_POST: 'FINISH_NOTIFICATION_POST',
  MARK_NOTIFICATION_AS_READ_BY_ID: 'MARK_NOTIFICATION_AS_READ_BY_ID',
  MARK_ALL_NOTIFICATIONS_AS_READ: 'MARK_ALL_NOTIFICATIONS_AS_READ',
  RECIVED_NOTIFICATIONS: 'RECIVED_NOTIFICATIONS'
}

// 开始请求
const startPost = () => {
  return {
    type: actionTypes.START_NOTIFICATION_POST
  }
}

// 请求结束
const finishPost = () => {
  return {
    type: actionTypes.FINISH_NOTIFICATION_POST
  }
}

// 根据id设置为已读
export const markNotificationAsReadById = (id) => {
  return async dispatch => {
    dispatch(startPost())
    postNotificationAsReadById(id)
      .then(res => {
        dispatch({
          type: actionTypes.MARK_NOTIFICATION_AS_READ_BY_ID,
          payload: {
            id
          }
        })
      })
    dispatch(finishPost())
  }
}

// 设置全部为已读
export const markAllNotificationsAsRead = () => {
  return dispatch => {
    dispatch(startPost())
    postAllNotificationAsRead()
      .then(res => {
        dispatch({
          type: actionTypes.MARK_ALL_NOTIFICATIONS_AS_READ
        })
      })
    dispatch(finishPost())
  }
}

// 获取消息列表
export const getNotificationList = () => {
  return async dispatch => {
    dispatch(startPost())
    getNotifications()
      .then(res => {
        dispatch({
          type: actionTypes.RECIVED_NOTIFICATIONS,
          payload: {
            list: res.data
          }
        })
      })
    dispatch(finishPost())
  }
}